package com.easy.carpanel.uart;


import android.content.Intent;
import android.util.Log;

/**
 * 七寸屏和设备串口通信
 * Created by yuanyi on 2020/5/30.
 */
public class uartCan {
    /**
     * 数据发送到can线
     * @param buffer  智慧派定义的数据结构形式
     */
    public void sendDate(byte[] buffer) {
        String data = byteArrayToHexString(buffer);
        Log.e("", "Activity cmdcan ===send bytes:" + data);
        Intent intent = new Intent();
        intent.setAction("com.unibroad.candata.receive");
        intent.putExtra("cmd", data);
//        sendBroadcast(intent);
//
//        //数据发送演示
//        strbuffer.append(">>>>发送：").append(data).append("\n");
//        data_tv.setText(strbuffer);
    }
//    private void addDataReceiver() {
//        IntentFilter mFilter = new IntentFilter();
//        mFilter.addAction("com.unibroad.candata.send");
//        registerReceiver(dataReceiver, mFilter);
//    }
//
//    private BroadcastReceiver dataReceiver = new BroadcastReceiver() {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();
//            if (action.equals("com.unibroad.candata.send")) {
//                String data = intent.getStringExtra("cmd");
//                byte[] bytes = hexStringToByte(data);
//                Log.e("", "Activity cmdcan ===receiver bytes:" + data);
//
//                //TODO 从can过来的数据接收处理演示
////                strbuffer.append(">>>>接收：").append(data).append("     ");
////                data_tv.setText(strbuffer);
////                sendDate(new byte[]{0x2E, (byte) 0x88, 0x0A, (byte) 0xAA, 0x02, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, 0x5D});
//            }
//        }
//    };

    /**
     * 字符串转Byte数组工具
     * @param hex
     * @return
     */
    private static byte[] hexStringToByte(String hex) {

        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static int toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }
    /**
     *  Byte数组转字符串工具
     * @param byteArray
     * @return
     */
    private static String byteArrayToHexString(byte[] byteArray) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (byteArray == null || byteArray.length <= 0) {
            return null;
        }
        for (int i = 0; i < byteArray.length; i++) {
            int v = byteArray[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

}